< previous page page_160 next page >

Page 160
The nSize parameter is declared as follows:
LPDWORD nSize // address of size of name buffer
Tutorial 6, "C++ Variables Meet Visual Basic," in Part III of this book, discusses porting C++ variables to Visual Basic. A DWORD is a 32-bit variable. The LP prefix suggests that the nSize parameter is actually a pointer to the size of the buffer, not the size itself. Right now, the function is declaring the BufferSize parameter (our name for nSize) as being passed ByVal. This means we are passing the size of the buffer, not a pointer to the size. The solution is to create a Long variable to hold the size and pass a pointer to that variable, which can be accomplished easily by simply removing the ByVal keyword and passing the parameter by reference.
That brings us to the following working code:
' Computer Name
' Copyright © 1998 by Desaware Inc. All Rights Reserved

Option Explicit

Private Declare Function GetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal ComputerName As String, BufferSize As Long) _
As Long

Private Const MAX_COMPUTERNAME_LENGTH = 15

Private Sub Form_Load()
   Dim s$
   Dim BufferLength As Long
   s$ = String$(MAX_COMPUTERNAME_LENGTH + 1, 0)
   BufferLength = MAX_COMPUTERNAME_LENGTH + 1
   Call GetComputerName(s$, BufferLength)
   lblName.Caption = s$
End Sub
The Missing Piece
What is actually loaded into the variable s$ buffer when this function returns? A NULL-terminated string. As a VB programmer, you don't want the NULL terminator character or anything after it. Can you come up with code to strip off the NULL terminator and the data that follows?

 
< previous page page_160 next page >